<template>
  <template v-if="style.isReady">
    <Teleport to="#attachmentsView" :disabled="!style.isReady">
      <div class="compo-signatureList h-full">
        <div class="box-noData" v-if="state.list.length == 0">
          <div>
            <img src="./images/noData-signature-list.png" alt="" />
            <div class="text">该文档中不包含签章</div>
          </div>
        </div>
        <div
          v-else
          @click="onAnchor(item)"
          class="item-signature cursor-pointer"
          v-for="item in state.list"
          :class="[
            item.validResult,
            {
              active:
                item.signatureDomainId ==
                provideHome.selectedSignature.signatureDomainId,
            },
          ]"
        >
          <div class="header">
            <div v-if="item.validResult == 'pass'" class="text-[#00943E]">
              验证成功
            </div>
            <div
              v-else-if="item.validResult == 'notpass'"
              class="text-[#C71023]"
            >
              验证失败
            </div>
            <div
              v-else-if="item.validResult == 'unknown'"
              class="text-[#64666B]"
            >
              未验证
            </div>
            <div class="text-primary" @click="onDetail(item)" can-click-trigger>
              <div class="box-trigger">
                <template v-if="item.validResult == 'unknown'"> 验证 </template>
                <template v-else>详情</template>
              </div>
            </div>
          </div>
          <div class="text-[11px] text-[#969AA0]">
            <div class="line1">签章人：{{ item.signer }}</div>
            <div>签章时间：{{ item.signatureTime }}</div>
            <div>位置：第{{ item.page }}页</div>
          </div>
        </div>
      </div>
    </Teleport>
  </template>
</template>
<script setup>
import {
  reactive,
  toRefs,
  onMounted,
  inject,
  watchEffect,
  nextTick,
} from "vue";
import $ from "jquery";
import { http, ss, seal,loading } from "@/utils";
import _ from "lodash";

/**
 * attachments 李代桃僵 "签章历史"，是因为新添加了trigger跟viewer，要想使他们之间联动，需修改 pdf.js 源码
 */
let $btnToggle = $("#viewAttachments");
let $viewer = $("#attachmentsView");

const provideHome = inject("provideHome");
const state = reactive({
  elViewer: $viewer[0],
  style: {
    isReady: false,
  },
  formData: {},
  list: [],
});
const { style, formData } = toRefs(state);

const init = () => {
  getSignatureList(true);
  $btnToggle.on("click", async function () {
    if ($btnToggle[0].dataset.isRequestList == undefined) {
      $btnToggle[0].dataset.isRequestList = 0;
    }
    getSignatureList();
  });
};

watchEffect(() => {
  let { signatureValidateResult } = provideHome;
  state.list.forEach(item => {
    let isValid =
      signatureValidateResult[
        seal.formatSignatureDomainId(item.signatureDomainId)
      ];
    let validResult = "unknown";
    if (typeof isValid == "boolean") {
      if (isValid) {
        validResult = "pass";
      } else {
        validResult = "notpass";
      }
    }
    _.assign(item, {
      validResult: validResult,
    });
    let $el = $(`[data-field-name="${item.signatureDomainId}"]`);
    if ($el.length) {
      $el[0].dataset.validResult = validResult;
    }
  });
});

const getSignatureList = async (isForce = false) => {
  if (isForce || $btnToggle[0].dataset.isRequestList == 0) {
    state.style.isReady = false;
    nextTick(async () => {
      loading.show({
        target:"#attachmentsView",
        background:'transparent'
      })
      let [err, res] = await http.post({
        data: {
          serviceCode: "verifyElectronicSealSignature",
          featureCode: "getFileElectronicSealSignatureList",
          businessData: {
            fileId: ss.get("fileId"),
          },
        },
      });
      state.style.isReady = true;
      loading.close();
      $btnToggle[0].dataset.isRequestList = 1;
      if (res) {
        state.list = res;
      }
    });
  }
};

provideHome.getSignatureList = getSignatureList;

const _anchorAccurate = signatureDomainId => {
  let $el = $(`[data-field-name="${signatureDomainId}"]`);
  if (!$el.isInViewport()) {
    $el[0].scrollIntoView({
      block: "center",
    });
  }
  $el.highLight();
};

//精确定位
let timer;
const anchorAccurate = (signatureDomainId, page) => {
  timer && clearTimeout(timer);
  let $el = $(`[data-field-name="${signatureDomainId}"]`);
  if ($el.length) {
    //签章节点已渲染出来
    // console.log("签章节点已渲染出来...");
    _anchorAccurate(signatureDomainId, page);
  } else {
    //签章节点未渲染出来，等待
    //定位到页面
    PDFViewerApplication.pdfLinkService.goToPage(page);
    // console.log("签章节点 未渲染出来");
    timer = setTimeout(() => {
      anchorAccurate(signatureDomainId, page);
    }, 100);
  }
};

const onAnchor = ({ signatureDomainId, page }) => {
  provideHome.selectedSignature.signatureDomainId = signatureDomainId;
  //定位到签章元素
  anchorAccurate(signatureDomainId, page);
};

let timer2;
const onDetail = ({ signatureDomainId }) => {
  timer2 && clearTimeout(timer2);
  let $el = $(`[data-field-name="${signatureDomainId}"]`);
  if ($el.isInViewport(0)) {
    setTimeout(() => {
      $el.trigger("click");
    }, 100);
  } else {
    timer2 = setTimeout(() => {
      onDetail({ signatureDomainId });
    }, 100);
  }
};

onMounted(() => {
  init();
});
</script>
<style lang="scss">
#attachmentsView {
  @apply w-full box-border;
}
.compo-signatureList {
  @apply mx-[6px];
  .item-signature {
    @apply p-2 pb-[12px] rounded-[4px] bg-white mb-[15px];
    // border-bottom: solid 1px #efefef;
    .header {
      @apply flex justify-between text-[12px] pb-2 mb-2;
      border-bottom: solid 1px #f3f3f4;
    }
    &:hover {
      box-shadow: 1px -4px 1px -1px inset #3461ff90;
    }
    &.active {
      box-shadow:
        0px 6px 18px 0px rgba(0, 0, 0, 0.08),
        1px -4px 1px -1px inset #3461ff;
    }
  }
}
</style>
